import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { useStore } from 'vuex';
import { computed } from 'vue';

const store = useStore();
const token = computed(() => store.state.auth.token);

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // 读取环境变量中的 API 地址
    timeout: 10000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        if (token.value) {
            config.headers = config.headers || {};
            config.headers['Authorization'] = `Bearer ${token.value}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data;
    },
    (error) => {
        console.error('Request Error:', error);
        return Promise.reject(error);
    }
);

// 封装请求方法
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
    return service.get(url, { params, ...config });
};

export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return service.post(url, data, config);
};

export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
    return service.put(url, data, config);
};

export const del = <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
    return service.delete(url, config);
};

export default service;
